package com.java.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.java.business.dao.AppointmentMapper;
import com.java.business.model.Appointment;
import com.java.business.model.PurchaseBill;
import com.java.business.model.WorkInfo;
import com.java.business.service.AppointmentService;
import com.java.business.util.SendSms;
import com.java.common.model.Result;
import com.java.common.util.JwtUtil;
import com.java.manage.model.*;
import com.java.manage.service.api.*;
import com.java.userservice.model.User;
import com.java.userservice.service.api.UserServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class AppointmentServiceImpl implements AppointmentService {

    @Autowired
    private AppointmentMapper appointmentMapper;

    @DubboReference
    private UserServiceApi userServiceApi;

    @DubboReference
    private BrandApiService brandApiService;

    @DubboReference
    private ColorApiService colorApiService;

    @DubboReference
    private ModelApiService modelApiService;

    @DubboReference
    private PlateApiService plateApiService;

    @DubboReference
    private CompanyApiService companyApiService;
    @Autowired
    private HttpServletRequest request;

    @Override
    public Result save(Appointment appointment) {
        appointment.setCreateTime(new Date());
        appointmentMapper.save(appointment);
        return Result.success();
    }

    @Override
    public Result modify(Appointment appointment) {
        appointmentMapper.modify(appointment);
        return Result.success();
    }

    @Override
    public Result remove(int[] ids) {
        for (int id : ids){
            appointmentMapper.remove(id);
        }
        return Result.success();
    }

    @Override
    public Result list(Appointment appointment) {
        PageHelper.startPage(appointment.getPageNum(), appointment.getPageSize());

        String token = request.getHeader("Token");
        Integer storeId = (Integer) JwtUtil.getClaims(token).get("storeId");
        appointment.setStoreId(storeId);

        List<Appointment> list = appointmentMapper.list(appointment);
        for (Appointment appoint : list) {
            if (appoint.getUserId() != null){
                // 用户表
                List<Integer> collect = list.stream().map(Appointment::getUserId).collect(Collectors.toList());
                List<User> users = userServiceApi.listByIds(collect);
                Map<Integer, User> userMap = users.stream().collect(Collectors.toMap(user -> user.getId(), user -> user));
                list.stream().forEach(app -> {
                    app.setUser(userMap.get(app.getUserId()));
                });
                // 品牌表
                List<Integer> brandCollect = list.stream().map(Appointment::getBrandId).collect(Collectors.toList());
                List<Brand> brands = brandApiService.listByIds(brandCollect);
                Map<Integer, Brand> brandMap = brands.stream().collect(Collectors.toMap(brand -> brand.getId(), brand -> brand));
                list.stream().forEach(app -> {
                    app.setBrand(brandMap.get(app.getBrandId()));
                });
                // 颜色表
                List<Integer> colorCollect = list.stream().map(Appointment::getColorId).collect(Collectors.toList());
                List<Color> colors = colorApiService.listByIds(colorCollect);
                Map<Integer, Color> colorMap = colors.stream().collect(Collectors.toMap(color -> color.getId(), color -> color));
                list.stream().forEach(app -> {
                    app.setColor(colorMap.get(app.getColorId()));
                });
                // 车型表
                List<Integer> modelCollect = list.stream().map(Appointment::getModelId).collect(Collectors.toList());
                List<Model> models = modelApiService.listByIds(modelCollect);
                Map<Integer, Model> modelMap = models.stream().collect(Collectors.toMap(model -> model.getId(), model -> model));
                list.stream().forEach(app -> {
                    app.setModel(modelMap.get(app.getModelId()));
                });
                // 车牌表
                List<Integer> plateCollect = list.stream().map(Appointment::getPlateId).collect(Collectors.toList());
                List<Licenseplate> licenseplates = plateApiService.listByIds(plateCollect);
                Map<Integer, Licenseplate> plateMap = licenseplates.stream().collect(Collectors.toMap(plate -> plate.getId(), plate -> plate));
                list.stream().forEach(app -> {
                    app.setPlate(plateMap.get(app.getPlateId()));
                });
                // 门店表
                List<Integer> storeCollect = list.stream().map(Appointment::getStoreId).collect(Collectors.toList());
                List<Company> companies = companyApiService.listByIds(storeCollect);
                Map<Integer, Company> companyMap = companies.stream().collect(Collectors.toMap(company -> company.getId(), company -> company));
                list.stream().forEach(app -> {
                    app.setStore(companyMap.get(app.getStoreId()));
                });
            }
        }

        PageInfo<Appointment> pageInfo = new PageInfo<>(list);

        Map<String, Object> map = new HashMap<>();
        map.put("list", pageInfo.getList());
        map.put("total", pageInfo.getTotal());
        return Result.success(map);
    }

    @Override
    public Result get(int id) {
        Appointment appointment = appointmentMapper.get(id);
        return Result.success(appointment);
    }

    @Override
    public Result sendSm(String phone, HttpServletRequest req) {
        Random r = new Random();// 用于作为随机数的验证码
        int i = r.nextInt(9999 - 1000 + 1) + 1000;
        String ph = phone.substring(0,11);
        try {
            SendSms sendSms = new SendSms();
            sendSms.sendSms(ph, String.valueOf(i),req);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.success();
    }
}
